package traditionalthread;

public class XunLeiInterview {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		final XunLeiThreadDemo2 demo = new XunLeiThreadDemo2();
		
		new Thread(){
			public void run(){
				/*while(true){
					int times =demo.ThreadA();
					if(times>=5)
						break;
				}*/
				for(int i=0;i<5;i++){
					demo.ThreadA();
				}
			}
		}.start();
		
		new Thread(new Runnable() {
			
			public void run() {
				for(int i=0;i<5;i++){
					demo.ThreadB();
				}
				
			}
		}).start();
    new Thread(new Runnable() {
			
			public void run() {
				for(int i=0;i<5;i++){
					demo.ThreadC();
				}
				
			}
		}).start();

	}

}
class XunLeiThreadDemo{
	private int nextThread = 1;
	private int threadATimes =0;
	private int threadBTimes =0;
	private int threadCTimes =0;
	public synchronized int ThreadA(){
		if(nextThread!=1){
			try {
				this.wait();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}else{
			System.out.println("A");
			nextThread=2;
			threadATimes++;
			notifyAll();
		}
		return threadATimes;
	}
	public synchronized int ThreadB(){
		if(nextThread!=2){
			try {
				this.wait();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}else{
			System.out.println("B");
			nextThread=3;
			threadBTimes++;
			notifyAll();
		}
		return threadBTimes;
	}

	public synchronized int ThreadC(){
		if(nextThread!=3){
			try {
				this.wait();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}else{
			System.out.println("C");
			nextThread=1;
			threadCTimes++;
			notifyAll();
		}
		return threadCTimes;
	}

}
class XunLeiThreadDemo2{
	private int nextThread = 1;
	private int threadATimes =0;
	private int threadBTimes =0;
	private int threadCTimes =0;
	public synchronized int ThreadA(){
		while(nextThread!=1){
			try {
				this.wait();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		System.out.println(threadATimes+1+" Times");
		System.out.println("A");
		nextThread=2;
		threadATimes++;
		notifyAll();
		return threadATimes;
	}
	public synchronized int ThreadB(){
		while(nextThread!=2){
			try {
				this.wait();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		System.out.println("B");
		nextThread=3;
		threadBTimes++;
		notifyAll();
		return threadBTimes;
	}

	public synchronized int ThreadC(){
		while(nextThread!=3){
			try {
				this.wait();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		System.out.println("C");
		nextThread=1;
		threadCTimes++;
		notifyAll();
		return threadCTimes;
	}

}